#include "stdafx.h"
#include "Forage.h"
#include "myRand.h"
#include "terrain.h"
#include "GoHome.h"
#include "Dead.h"
#include "Ant.h"

extern int terrain[kMaxRows][kMaxCols];

CForage * CForage::instance()
{
	static CForage inst;
	return (&inst);
}

void CForage::Enter(CAnt *pAnt)
{	
}

void CForage::Execute(CAnt *pAnt)
{
	int rowMove;
	int colMove;
	int newRow;
	int newCol;
	int foodRow;
	int foodCol;
	int poisonRow;
	int poisonCol;

	rowMove = rnd(0,2)-1;
	colMove = rnd(0,2)-1;
	newRow = pAnt->row + rowMove;
	newCol = pAnt->col + colMove;
	if(newRow < 0) return;
	if(newCol < 0) return;
	if(newRow >= kMaxRows-1) return;
	if(newCol >= kMaxCols-1) return;
	if((terrain[newRow][newCol] == kGround) ||
		(terrain[newRow][newCol] == kWater)){
			pAnt->row = newRow;
			pAnt->col = newCol;
	}
	if(terrain[newRow][newCol] == kFood){
		pAnt->row = newRow;
		pAnt->col = newCol;
		terrain[pAnt->row][pAnt->col] = kGround;
//		state = kGoHome;
		do{
			foodRow = rnd(0,kMaxRows-1);
			foodCol = rnd(0,kMaxCols-1);
		}while(terrain[foodRow][foodCol] != kGround);
		terrain[foodRow][foodCol] = kFood;
		pAnt->changeState(CGoHome::instance());
	}
	if(terrain[newRow][newCol] == kPoison){
		pAnt->row = newRow;
		pAnt->col = newCol;
		terrain[pAnt->row][pAnt->col] = kGround;
		
//		state = kDead;
		do {
			poisonRow = rnd(0,kMaxRows-1);
			poisonCol = rnd(0,kMaxCols-1);
		}while(terrain[poisonRow][poisonCol] != kGround);
		terrain[poisonRow][poisonCol] = kPoison;
		pAnt->changeState(CDead::instance());
	}
}

void CForage::Exit(CAnt *pAnt)
{
}